<?php

namespace Modules\Card\Entities;

use Modules\Core\Entities\BaseEntity as Model;
use ThrowException;
use Modules\Order\Traits\Skuable;

// 道具卡券
class Card extends Model
{
    use Skuable;

    protected $guarded = [];
    protected $table = 'cards';

    static public $resourceName = '道具卡';

    protected $casts = [
    ];

    static public function getCardByType($type)
    {
    	return self::where('type', $type)->first();
    }

    static public function addUsedCountByType($type, $total)
    {
        return self::where('type', $type)->first()->addUsedCount($total);
    }

    // 用户兑换
    public function buyForUser($user, $total = 1)
    {
    	$scorePrice = $this->score_price * $total;

    	if ($this->stock < $total) {
    		ThrowException::Conflict('库存不足~');
    	}

    	// 扣除积分
        $user->asset('score')->out($scorePrice, [
            'description' => '兑换' . $this->title
        ]) || ThrowException::Conflict('积分不足哦~');

        $this->addSales($total);

        $user->card_asset($this->type)->in($total, [
        	'description' => '兑换获得'
        ]);
    }

    // 发放给用户
    public function sendToUser($user, $total, $options = [])
    {
        $this->addSales($total);
        $user->card_asset($this->type)->in($total, [
            'description' => $options['description']
        ]);
    }

    public function addUsedCount($total)
    {
        $this->used_count++;
        $this->save();
    }
}
